//
// Copyright (C) 2009 Ben Jaques.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// - Neither the name of the author nor the names of its contributors may be used
//   to endorse or promote products derived from this software without specific
//   prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

/*
 * AddAppDialog.java
 *
 * Created on Aug 28, 2009, 4:25:26 PM
 */
package uk.co.massycat.appreviewsfinder;

import uk.co.massycat.appreviewsfinder.countries.CountriesManager;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.Timer;
import javax.swing.event.DocumentEvent;

/**
 *
 * @author ben
 */
public class SearchAppDialog extends javax.swing.JDialog {

    private Timer mAutoFindTimer;
    private AppSearchResult mSearchResult;

    protected void autoFindTimerFired() {
        mOkButton.setEnabled(false);

        // Form the iTune Store id
        int itunes_code = CountriesManager.getManager().getITunesCodeForCountry(AppPreferences.getPreferences().getSearchCountry());
        String iTunesCode = Integer.toString(itunes_code) + ",2";

        try {
            String safe_string = URLEncoder.encode(mAppNameTextField.getText(), "UTF-8");
            String http_string = "http://ax.search.itunes.apple.com/WebObjects/MZSearchHints.woa/wa/hints?media=software&q=" +
                    safe_string;

            //System.out.println("Safe: " + safe_string + "\nHttp: " + http_string);
            String result_xml = Utilities.connectAndGetResponse(http_string, iTunesCode);

            // parse the search results and setup the list accordingly
            //System.out.println("Search results:\n" + result_xml);

            DefaultListModel model = (DefaultListModel) mAppList.getModel();
            model.clear();

            SearchTermReader reader = new SearchTermReader(result_xml);
            List<SearchTermResult> apps = reader.getApps();

            Iterator<SearchTermResult> iterator = apps.iterator();

            while (iterator.hasNext()) {
                SearchTermResult app = iterator.next();

                model.addElement(app);
            }
        } catch (Exception e) {
        }
    }

    public AppSearchResult getResult() {
        return mSearchResult;
    }


    /** Creates new form AddAppDialog */
    public SearchAppDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        mOkButton.setEnabled(false);

        mAppNameTextField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                mAutoFindTimer.restart();
            }

            public void removeUpdate(DocumentEvent e) {
                mAutoFindTimer.restart();
                //System.out.println("removeUpdate");
            }

            public void changedUpdate(DocumentEvent e) {
                //System.out.println("changedUpdate");
            }
        });

        mAutoFindTimer = new Timer(750, new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                autoFindTimerFired();
            }
        });

        mAutoFindTimer.setRepeats(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        mAppList = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        mCancelButton = new javax.swing.JButton();
        mOkButton = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        mAppNameTextField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Search for App");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jPanel2.setLayout(new java.awt.BorderLayout());

        mAppList.setModel(new javax.swing.DefaultListModel());
        mAppList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        mAppList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                mAppListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(mAppList);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        mCancelButton.setText("Cancel");
        mCancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mCancelButtonActionPerformed(evt);
            }
        });
        jPanel1.add(mCancelButton);

        mOkButton.setText("Ok");
        mOkButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mOkButtonActionPerformed(evt);
            }
        });
        jPanel1.add(mOkButton);

        jPanel2.add(jPanel1, java.awt.BorderLayout.SOUTH);

        jLabel1.setText("Enter search term:");
        jPanel3.add(jLabel1);

        mAppNameTextField.setColumns(20);
        mAppNameTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mAppNameTextFieldActionPerformed(evt);
            }
        });
        jPanel3.add(mAppNameTextField);

        jPanel2.add(jPanel3, java.awt.BorderLayout.NORTH);

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        mAutoFindTimer.stop();
    }//GEN-LAST:event_formWindowClosed

    private void mAppNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mAppNameTextFieldActionPerformed
        mAutoFindTimer.stop();
        autoFindTimerFired();
    }//GEN-LAST:event_mAppNameTextFieldActionPerformed

    private void mCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mCancelButtonActionPerformed
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_mCancelButtonActionPerformed

    private void mOkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mOkButtonActionPerformed
        // if something is selected then do a search on that
        SearchTermResult result = (SearchTermResult) mAppList.getSelectedValue();
        if (result != null) {
            // Find the apps for the search url and show them
            //System.out.println("Search url: " + result.mURL);
            AddAppDialog add_dialog = new AddAppDialog( this, true, result.mURL);
            add_dialog.setLocationRelativeTo(this);
            add_dialog.setVisible(true);

            mSearchResult = add_dialog.getResult();

            if ( mSearchResult != null) {
                this.setVisible(false);
                this.dispose();
            }
        }
    }//GEN-LAST:event_mOkButtonActionPerformed

    private void mAppListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_mAppListValueChanged
        if (evt.getValueIsAdjusting() == false) {

            if (mAppList.getSelectedIndex() != -1) {
                mOkButton.setEnabled(true);
            }
        }
    }//GEN-LAST:event_mAppListValueChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                SearchAppDialog dialog = new SearchAppDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList mAppList;
    private javax.swing.JTextField mAppNameTextField;
    private javax.swing.JButton mCancelButton;
    private javax.swing.JButton mOkButton;
    // End of variables declaration//GEN-END:variables
}
